﻿using Abp.Collections.Extensions;
using Abp.Dependency;
using Abp.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AbpProjectTemplate.Utilities.Enums
{
    public static class EnumHelper
    {
        private static List<Type> _enumTypes = new List<Type>();
        private static List<Assembly> _regedAssemblies = new List<Assembly>();
        /// <summary>
        /// 注册程序集中的所有枚举类型到管理中
        /// </summary>
        public static void RegisterAssembly(Assembly assembly)
        {
            if (_regedAssemblies.Any(t => t.FullName == assembly.FullName))
                return;
            _regedAssemblies.Add(assembly);
            var types = assembly.GetTypes()
              .Where(t => t.IsEnum && t.IsPublic);
            _enumTypes.AddRange(types);

        }
        public static void RegisiterEnum(this IIocManager iocManager)
        {
            iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
            {
                RegisterAssembly(handler.ComponentModel.Implementation.Assembly);
            };
        }
        /// <summary>
        /// 获取当前系统所有的枚举类型
        /// </summary>
        public static IEnumerable<Type> GetAllTypes() 
        {
            return _enumTypes;
        }
        /// <summary>
        /// 获取指定类型的枚举数据
        /// </summary>
        public static List<EnumItem> GetItems(Type enumType)
        {
            var ops = Enum.GetValues(enumType);
            var items = new List<EnumItem>();
            foreach (var o in ops)
            {
                var item = new EnumItem();
                //var key = o.GetLanguateKey();
                item.Value = Convert.ToInt32(o);
                item.Name = o.ToString();
                item.Desc = o.GetDesc(false);
                items.Add(item);
            }
            return items;
        }
        /// <summary>
        /// 获取指定类型的枚举数据
        /// </summary>
        public static List<EnumItem> GetItems<TEnum>()
        {
            return GetItems(typeof(TEnum));
        }
        /// <summary>
        /// 获取所有指定名称的枚举列表
        /// </summary>
        public static IDictionary<string, List<EnumItem>> GetAllItems(Func<Type, bool> predicate = null)
        {
            var types = _enumTypes.WhereIf(predicate != null, predicate);

            var dic = new Dictionary<string, List<EnumItem>>();
            foreach (var type in types)
            {
                dic.Add(type.Name, GetItems(type));
            }

            return dic;
        }
        /// <summary>
        /// 获取所有需要返回给客户端的枚举项
        /// </summary>
        public static IDictionary<string, List<EnumItem>> GetShowOnApiItems()
        {
            return GetAllItems(t => t.CustomAttributes.Any(x => x.AttributeType == typeof(ShowOnApiAttribute)));
        }
    }
}
